package com.hmall.gateway.filters;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.common.exception.UnauthorizedException;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor//用构造函数注入
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    //注入配置类,可以用构造函数注入，也可以用@Autowired注入
    private final AuthProperties authProperties;
    private final JwtTool jwtTool;
    //路径匹配器
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 1.获取Request
        ServerHttpRequest request = exchange.getRequest();

        // 2.判断是否需要做登录校验拦截
        //路径校验
        if (isExclude(request.getPath().toString())) {
            //放行
            return chain.filter(exchange);
        }

        // 3.获取token
        String token=null;
        List<String> headers = request.getHeaders().get("authorization");
        if (headers != null&& !headers.isEmpty()){
            //默认拿到的token对应的请求头只有一个，所以拿集合中的第一个
            token = headers.get(0);
        }

        // 用户id
        Long userId =null;
        // 4.校验并解析token
        try {
            userId = jwtTool.parseToken(token);
        } catch (UnauthorizedException e) {
            // 401 用状态码标志未拦截，设置响应状态码为401
            //拿到响应
            ServerHttpResponse response = exchange.getResponse();
            //设置响应状态码401
            response.setRawStatusCode(401);
            // 返回
            return response.setComplete();
        }

        // 5.传递用户信息 swe
        String userInfo=userId.toString();
        ServerWebExchange swe = exchange.mutate()
                //请求头需约定好,前面是key，后面是value，将数据传出去
                .request(builder -> builder.header("user-info", userInfo))
                .build();

        // 6.放行,将获取到的信息传到下一个过滤器
        return chain.filter(swe);

    }

    private boolean isExclude(String path) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(pathPattern,path)) {
                // 如果匹配到返回true
                return true;
            }
        }
        // 匹配不到返回false
        return false;
    }

    //定义过滤器优先级
    @Override
    public int getOrder() {
        //优先级，数字越小优先级越高
        return 0;
    }

}
